package com.atguigu.springcloud.service.impl;

import com.atguigu.springcloud.service.PaymentService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.stereotype.Service;
import java.util.concurrent.TimeUnit;

@Service
public class PaymentServiceImpl implements PaymentService {

    //成功
    public String paymentInfo_OK(Integer id){
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "线程池："+Thread.currentThread().getName()+"   paymentInfo_OK,id：  "+id+"\t"+"哈哈哈"  ;
    }

    //失败
    // @HystrixCommand 执行 Hystrix 相关设置
    @HystrixCommand(
        // fallbackMethod 属性：指定当前方法失败后，要调用的备选方法
        fallbackMethod = "payment_TimeoutFallBack",

        // commandProperties 属性：指定其它参数
        commandProperties = {
            // 指定超时时间：当前方法超过 5000 毫秒就判定为失败
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "5000")
        }
    )
    public String payment_Timeout(Integer id){
        int timeNumber = 3;
        try { TimeUnit.SECONDS.sleep(timeNumber); }catch (Exception e) {e.printStackTrace();}
        return "线程池："+Thread.currentThread().getName()+"   paymentInfo_TimeOut,id：  "+id+"\t"+"呜呜呜"+" 耗时(秒)"+timeNumber;
    }

    // 专门声明一个方法，作为正常业务方法失败后的备选方法
    public String payment_TimeoutFallBack(Integer id) {
        return "抱歉！系统忙，请稍后再试！id = " + id + " 线程名：" + Thread.currentThread().getName();
    }

    @HystrixCommand(
        fallbackMethod = "paymentCircuitBreakerFallback",
        commandProperties = {
            // 开启断路器
            @HystrixProperty(name = "circuitBreaker.enabled", value = "true"),

            // 在限定时间内，发送够多少个请求才能打开断路器
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "1"),

            // 断路器从全开到半开状态中间的时间长度
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "15000")
        }
    )
    public String paymentCircuitBreaker(Integer id) {

        if (id > 50) {
            throw new RuntimeException("[Provider] paymentCircuitBreaker() 我疯啦！");
        }

        return "[Provider] paymentCircuitBreaker() 正常。";
    }

    public String paymentCircuitBreakerFallback(Integer id) {
        return "[Provider] paymentCircuitBreaker() 降级方案。id = " + id;
    }
}